
import { getFilterData, setFilterData } from '@/api/setting';
const jsonParse = (str) => {
  try {
    return JSON.parse(str);
  } catch (error) {
    return str;
  }
};

const filter = {
  state: {
    filterConfig: null
  },
  mutations: {
    SET_FILTERCONFIG: (state, data) => {
      state.filterConfig = data;
    }
  },
  actions: {
    getFilterConfig({ commit }) {
      return new Promise((resolve, reject) => {
        getFilterData().then(res => {
          if (res.code === 200 && res.data) {
            const config = res.data.config ? jsonParse(res.data.config) : '';
            if (config.resource) {
              // 删除资源列表中旧的快捷筛选，因为在 v3.3.9 筛选结构变了
              config.resource = config.resource.filter(i => !i.filterParams);
            }
            commit('SET_FILTERCONFIG', config);
            resolve(config);
          } else {
            reject(res.message);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 设置
    setFilterConfig({ commit }, config) {
      return new Promise((resolve, reject) => {
        const data = { config };
        if (data.config && typeof data.config === 'object') {
          data.config = JSON.stringify(data.config);
        }
        setFilterData(data).then(res => {
          if (res.code === 200) {
            commit('SET_FILTERCONFIG', config);
            resolve(res);
          } else {
            reject(res.message);
          }
        }).catch(error => {
          // 测试代码
          commit('SET_FILTERCONFIG', config);
          reject(error);
        });
      });
    }
  }
};

export default filter;
